const fs = require('fs');
const path = require('path');

const authConfigPath = path.join(__dirname, '../src/config/auth.js');

function toggleAuth(enable = null) {
  try {
    // 读取当前配置
    const configContent = fs.readFileSync(authConfigPath, 'utf8');
    
    // 解析当前状态
    const enableAuthMatch = configContent.match(/enableAuth:\s*(true|false)/);
    const enableRoleCheckMatch = configContent.match(/enableRoleCheck:\s*(true|false)/);
    
    const currentAuthState = enableAuthMatch ? enableAuthMatch[1] === 'true' : false;
    const currentRoleState = enableRoleCheckMatch ? enableRoleCheckMatch[1] === 'true' : false;
    
    // 如果未指定状态，则切换当前状态
    const newAuthState = enable !== null ? enable : !currentAuthState;
    const newRoleState = enable !== null ? enable : !currentRoleState;
    
    // 更新配置内容
    let newContent = configContent
      .replace(/enableAuth:\s*(true|false)/, `enableAuth: ${newAuthState}`)
      .replace(/enableRoleCheck:\s*(true|false)/, `enableRoleCheck: ${newRoleState}`);
    
    // 写入文件
    fs.writeFileSync(authConfigPath, newContent);
    
    console.log(`✅ Auth验证已${newAuthState ? '启用' : '禁用'}`);
    console.log(`✅ 角色验证已${newRoleState ? '启用' : '禁用'}`);
    console.log(`📁 配置文件: ${authConfigPath}`);
    
    if (!newAuthState) {
      console.log('💡 提示: 现在所有API都不需要认证即可访问');
    } else {
      console.log('💡 提示: 现在API需要认证才能访问');
    }
    
  } catch (error) {
    console.error('❌ 切换auth状态失败:', error.message);
    process.exit(1);
  }
}

// 处理命令行参数
const args = process.argv.slice(2);
const command = args[0];

switch (command) {
  case 'enable':
    toggleAuth(true);
    break;
  case 'disable':
    toggleAuth(false);
    break;
  case 'status':
    try {
      const configContent = fs.readFileSync(authConfigPath, 'utf8');
      const enableAuthMatch = configContent.match(/enableAuth:\s*(true|false)/);
      const enableRoleCheckMatch = configContent.match(/enableRoleCheck:\s*(true|false)/);
      
      const authState = enableAuthMatch ? enableAuthMatch[1] === 'true' : false;
      const roleState = enableRoleCheckMatch ? enableRoleCheckMatch[1] === 'true' : false;
      
      console.log('🔐 Auth验证状态:');
      console.log(`   Auth验证: ${authState ? '✅ 启用' : '❌ 禁用'}`);
      console.log(`   角色验证: ${roleState ? '✅ 启用' : '❌ 禁用'}`);
    } catch (error) {
      console.error('❌ 获取状态失败:', error.message);
    }
    break;
  case 'toggle':
  default:
    toggleAuth();
    break;
}

console.log('\n📖 使用方法:');
console.log('  node scripts/toggle-auth.js enable   # 启用auth验证');
console.log('  node scripts/toggle-auth.js disable  # 禁用auth验证');
console.log('  node scripts/toggle-auth.js toggle   # 切换auth验证状态');
console.log('  node scripts/toggle-auth.js status   # 查看当前状态'); 